<script>
import {login} from "@/middleware/interface";
import {ElMessage} from "element-plus";

export default {
  data() {
    return {
      showPwd: false,
      username: "",
      password: "",
    };
  },
  mounted() {
    if (localStorage.token) {
      this.toHome()
    }
  },
  methods: {
    click() {
    },
    toHome() {
      this.$router.push({path: '/home', replace: true})
    },
    async submitLogin() {
      if (this.username === "" || this.password === "") {
        ElMessage.info("用户名和密码不能为空")
        return
      }
      const res = await login({
        "username": this.username,
        "password": this.password,
      });
      if (res.code) {
        ElMessage.success("登录成功！")
        localStorage.token = res.data
        this.toHome()
      } else {
        ElMessage.error(res.msg)
        localStorage.token = ""
      }
    }
  },
};
</script>

<template>
  <div class="w-full flex justify-center">
    <div
        class="bg-white w-full max-w-md mx-5 px-3 py-5 rounded-2xl flex flex-col items-center mt-8"
    >
      <img class="w-24 h-24" src="../assets/img/logo.png" alt=""/>
      <div class="h-5"></div>
      <input
          type="text"
          class="rounded-xl w-full max-w-xs bg-gray-100 px-5 py-4 outline-none"
          placeholder="账号"
          v-model="username"
      />
      <div class="h-2"></div>
      <div class="relative w-full max-w-md flex justify-center">
        <div class="rounded-xl w-full max-w-xs bg-gray-100 px-5 py-4 flex justify-between">
          <input @keydown.enter="submitLogin()" :type="showPwd ? 'text' : 'password'" class=" flex-1 outline-none bg-transparent" placeholder="密码"
                 v-model="password"/>
          <div class="">
            <img
                @click="showPwd = !showPwd"
                v-if="!showPwd"
                class="w-5 h-5 select-none cursor-pointer"
                src="../assets/img/visible.svg"
                alt=""
            />
            <img
                @click="showPwd = !showPwd"
                v-else
                class="w-5 h-5 select-none cursor-pointer"
                src="../assets/img/invisible.svg"
                alt=""
            />
          </div>
        </div>
      </div>
      <div
          class="text-white px-12 py-2.5 rounded-xl mt-6 mb-4 cursor-pointer transition select-none hover:bg-black"
          style="background: #30170e"
          @click="submitLogin()"
      >
        登录
      </div>
    </div>
  </div>
</template>

<style scoped></style>
